package cn.tx;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * RabbitMq工具类
 * @author Mxb
 * @version 1.0
 * @date 2020/10/4 11:28
 */
public class RabbitMQUtils {
    private static ConnectionFactory connectionFactory;

    static {
        //创建连接工厂
        connectionFactory = new ConnectionFactory();
        //设置相关参数
        connectionFactory.setHost("192.168.64.121");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("sxt");
        connectionFactory.setPassword("123456");
        connectionFactory.setVirtualHost("/v-sxt");
    }

    /**
     * 提供一个获取连接的方法
     */
    public static Connection getConnection() {
        try {
            //从连接工厂里面创建一个连接
            Connection connection = connectionFactory.newConnection();
            return connection;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 提供一个可以关闭通道和连接的方法
     */
    public static void closeChannelAndConnection(Channel channel, Connection
            connection) {
        try {
            if (null != channel) channel.close();
            if (null != connection) connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
